package com.mall.biz.trade.impl.o2o.incluce;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mall.biz.trade.O2OTradeBiz;
import com.mall.client.eshop.EshopTradeService;
import com.mall.client.trade.TradeService;
import com.mall.client.user.UserExtendedService;
import com.mall.client.user.UserService;
import com.mall.dto.TradePriceAndBuyCountDTO;
import com.mall.pojo.EshopTrade;
import com.mall.pojo.Trade;
import com.mall.pojo.UserExtended;
@Service
public class BalanceTradeImpl implements O2OTradeBiz {
	private static final Logger log = LoggerFactory.getLogger(BalanceTradeImpl.class);
	
	@Autowired
	private UserService userService;
	@Autowired
	private UserExtendedService userExtendedService;
	@Autowired
	private TradeService tradeService;
	@Autowired
	private EshopTradeService eshopTradeService;
	
	@Override
	public TradePriceAndBuyCountDTO pack4PirceAndBuyCount(HttpServletRequest request, Integer type, Long price,
			Integer buyCount, Long parentId) {
		TradePriceAndBuyCountDTO tradePriceAndBuyCountDTO = new TradePriceAndBuyCountDTO();
		tradePriceAndBuyCountDTO.setPrice(price);
		tradePriceAndBuyCountDTO.setBuyCount(1);
		return tradePriceAndBuyCountDTO;
	}

	@Override
	public Boolean afterSuccInsert(HttpServletRequest request, Trade trade) {
		UserExtended userExtended = this.userExtendedService.getUserExtendByUserId(trade.getBuyUserId());
		if(userExtended == null){
			throw new RuntimeException("用户扩展表不存在");
		}
		if(userExtended.getBalance() < trade.getPrice()){
			throw new RuntimeException("余额不足");
		}
		if(userExtended.getBond() == null){
			userExtended.setBond(0l);
		}
		userExtended.setBalance(userExtended.getBalance()-trade.getPrice());
		userExtended.setBond(userExtended.getBond()+trade.getPrice());
		this.userExtendedService.updateExtendedByPrimaryKey(userExtended);
		EshopTrade eshopTrade = this.eshopTradeService.getEshopTradeByEshopTradeId(trade.getParentId());
		if("支付定金".equals(trade.getDiscountMess())){
			trade.setStatus(1);
			eshopTrade.setStatus(1);
		}else if("支付全款".equals(trade.getDiscountMess())){
			trade.setStatus(2);
			eshopTrade.setStatus(2);
		}
		this.tradeService.updateTradeByTrade(trade);
		this.eshopTradeService.modifyEshopTradeByEshopTrade(eshopTrade);
		return true;
	}

	@Override
	public Boolean afterErrorInsert(HttpServletRequest request, Trade trade) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Boolean beforeInsert(HttpServletRequest request, Trade trade) {
		// TODO Auto-generated method stub
		return null;
	}

}
